<template>
  <el-dialog
    v-el-drag-dialog
    :title="type === 'add' ? '新增商品' : '编辑商品'"
    :visible.sync="visible"
    width="700px"
    @closed="reset"
  >
    <el-tabs v-model="activeName" type="card">
      <el-tab-pane label="商品信息" name="first">
        <el-form ref="dataForm" class="form" :rules="rules" :model="temp" label-position="right" label-width="100px">
          <el-form-item style="width: 100%;" label="类型:">
            <span>{{ currentGoodsType.gtName }}</span>
          </el-form-item>
          <el-form-item label="编码:" prop="goodsCode">
            <el-input v-model="temp.goodsCode" :disabled="type==='edit'" :maxlength="10" clearable>
              <el-button v-if="type === 'add'" slot="append" class="append-search" @click.prevent="getCode">获取</el-button>
            </el-input>
          </el-form-item>
          <el-form-item label="名称:" prop="goodsName">
            <el-input v-model="temp.goodsName" :maxlength="20" clearable placeholder="请输入" />
          </el-form-item>
          <el-form-item label="单位:" prop="unitId">
            <el-select v-model="temp.unitId" clearable placeholder="请选择">
              <el-option v-for="item in unitIdMap" :key="item.value" :label="item.desc" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="别名:" prop="aliasName">
            <el-input v-model="temp.aliasName" :maxlength="50" clearable placeholder="请输入" />
          </el-form-item>
          <el-form-item label="体积:" prop="cubage">
            <el-input-number v-model="temp.cubage" :controls="false" :min="0" :max="99999999" :pression="0" clearable placeholder="请输入" style="width: 100%;" />
          </el-form-item>
          <el-form-item label="重量:" prop="weight">
            <el-input-number v-model="temp.weight" :controls="false" :min="0" :max="99999999" :pression="2" clearable placeholder="请输入" style="width: 100%;" />
          </el-form-item>
          <el-form-item label="型号:" prop="specId">
            <el-select v-model="temp.specId" filterable clearable placeholder="请选择">
              <el-option v-for="item in specListAll" :key="item.specId" :label="item.specName" :value="item.specId" />
            </el-select>
          </el-form-item>
          <el-form-item label="计价方式:" prop="pricingMode">
            <el-select v-model="temp.pricingMode" placeholder="请选择">
              <el-option label="按包装计费" :value="1" />
              <el-option label="按单位计费" :value="2" />
            </el-select>
          </el-form-item>
          <el-form-item label="配送费用:" prop="deliveryFun">
            <el-input-number v-model="temp.deliveryFun" :controls="false" :min="0" :max="99999999" disabled placeholder="请输入" style="width: 100%;" />
          </el-form-item>
          <el-form-item label="上楼费:" prop="floorFun">
            <el-input-number v-model="temp.floorFun" :controls="false" :min="0" :max="99999999" disabled placeholder="请输入" style="width: 100%;" />
          </el-form-item>
          <el-form-item label="押金:" prop="cashPledge">
            <el-input-number v-model="temp.cashPledge" :controls="false" :min="0" :max="99999999" clearable placeholder="请输入" style="width: 100%;" />
          </el-form-item>
          <el-form-item label="退残单价:" prop="returnPrice">
            <el-input-number v-model="temp.returnPrice" :controls="false" :min="0" :max="99999999" :pression="2" clearable placeholder="请输入" style="width: 100%;" />
          </el-form-item>
          <el-form-item label="商品状态:" prop="gdStatus">
            <el-select v-model="temp.gdStatus" multiple placeholder="请选择">
              <el-option v-for="item in gdStatusMap" :key="item.value" :label="item.desc" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="商品性质:" prop="gdProperty">
            <el-select v-model="temp.gdProperty" placeholder="请选择" clearable>
              <el-option v-for="item in gdPropertyMap" :key="item.value" :label="item.desc" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item v-if="currentGoodsType.gtCategory===4" label="积分兑换:" prop="exchangeFlag">
            <el-select v-model="temp.exchangeFlag" placeholder="请选择">
              <el-option label="不可兑换" :value="1" />
              <el-option label="可兑换" :value="2" />
            </el-select>
          </el-form-item>
          <el-form-item style="width: 50%;" label="营销渠道:" prop="saleMode">
            <el-select v-model="temp.saleMode" multiple placeholder="请选择">
              <el-option v-for="item in goodsChannel" :key="item.value" :label="item.desc" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item v-if="currentGoodsType.gtCategory!==4" style="width: 50%; color: red;" label-width="0" prop="csmPhone">
            *微信端渠道不支持按单位计价商品
          </el-form-item>
          <el-form-item label="其他:" class="block">
            <el-checkbox v-model="sys_goods_edit_options_1">不统计库存</el-checkbox>
            <el-checkbox v-model="sys_goods_edit_options_2">启用轻重转换</el-checkbox>
            <el-checkbox v-model="sys_goods_edit_options_3">可押</el-checkbox>
            <el-checkbox v-model="sys_goods_edit_options_4">可欠</el-checkbox>
            <el-checkbox v-model="sys_goods_edit_options_5">无需扫码</el-checkbox>
          </el-form-item>
          <el-form-item label="使用范围:" style="width: 50%;" prop="radio">
            <el-radio v-model="temp.radio" label="1">不限</el-radio>
            <el-radio v-model="temp.radio" label="2">自定义</el-radio>
          </el-form-item>
          <el-form-item v-show="temp.radio === '2'" style="width: 50%;" label-width="0" prop="orgIds">
            <el-tree-select
              v-model="temp.orgIds"
              :clearable="false"
              class="tree-select"
              :popover-width="360"
              :select-params="{
                clearable: true,
                multiple: true,
                placeholder: '请选择',
                loading: $loadingPlugin.getTreeData
              }"
              :tree-params=" {
                'default-expand-all': true,
                'expand-on-click-node': false,
                'highlight-current': true,
                props:{
                  value:'orgId',
                  label: 'orgName',
                  disabled: 'disabled',
                },
                data: treeData
              }"
            />
          </el-form-item>
          <el-form-item label="显示顺序:" prop="showIndex" class="block">
            <el-input v-model="temp.showIndex" controls-position="right" :min="0" :max="99999999" clearable placeholder="请输入" />
          </el-form-item>
          <el-form-item label="描述:" prop="remark" class="block">
            <el-input v-model="temp.remark" type="textarea" :rows="5" :maxlength="1000" show-word-limit />
          </el-form-item>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="扩展信息" name="second">
        <el-tabs v-model="additionTab" :tab-position="'right'">
          <el-tab-pane label="图文详情" name="first">
            <fu-editor ref="fuEditor1" :content="temp.extends1" />
          </el-tab-pane>
          <el-tab-pane label="产品参数" name="second">
            <fu-editor ref="fuEditor2" :content="temp.extends2" />
          </el-tab-pane>
          <el-tab-pane label="售后保障" name="third">
            <fu-editor ref="fuEditor3" :content="temp.extends3" />
          </el-tab-pane>
          <el-tab-pane label="税务信息" name="forth">
            <el-form class="form" :model="temp" label-position="right" label-width="80px">
              <el-form-item label="商品简码:" prop="goodsShortCode">
                <el-input v-model="temp.goodsShortCode" placeholder="请输入" />
              </el-form-item>
              <el-form-item label="是否使用优惠政策" label-width="120" prop="isPreferential">
                <el-checkbox v-model="temp.isPreferential" />
              </el-form-item>
              <el-form-item label="税率标识:" prop="taxRateFlag">
                <el-select v-model="temp.taxRateFlag" placeholder="请选择">
                  <el-option v-for="item in taxRateFlagMap" :key="item.value" :label="item.desc" :value="item.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="税率:" prop="taxRate">
                <el-input v-model="temp.taxRate" style="width: 90%;" placeholder="请输入" />
                %
              </el-form-item>

            </el-form>
          </el-tab-pane>
        </el-tabs>

      </el-tab-pane>

    </el-tabs>

    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false">
        关闭
      </el-button>
      <el-button :loading="$loadingPlugin.add || $loadingPlugin.edit" type="primary" @click="success">
        保存
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
  import { queryMap, queryOrgCode, querySpecListAll, goodsAdd, queryGoodsDefaultData } from '@/api'
  import { mapGetters } from 'vuex'
  import getTreeData from '@/utils/jsonTree'
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'
  import FuEditor from '@/components/FuCkEditor'

  export default {
    name: 'add',
    components: {
      FuEditor
    },
    data() {
      return {
        visible: false,
        type: 'add',
        activeName: 'first',
        additionTab: 'first',
        treeData: [],
        currentGoodsType: {
          gtName: ''
        },
        specListAll: [],
        unitIdMap: [],
        gdStatusMap: [],
        gdPropertyMap: [],
        goodsChannel: [{ value: 1, desc: '呼叫中心' }, { value: 2, desc: '微信端' }],
        taxRateFlagMap: [],
        goodsId: 0,
        sys_goods_edit_options_1: false,
        sys_goods_edit_options_2: false,
        sys_goods_edit_options_3: false,
        sys_goods_edit_options_4: false,
        sys_goods_edit_options_5: false,
        temp: {
          goodsCode: '',
          goodsName: '',
          unitId: '',
          aliasName: '',
          cubage: 0,
          weight: 0,
          specId: '',
          pricingMode: 1,
          deliveryFun: 0,
          floorFun: 0,
          cashPledge: 0,
          returnPrice: 0,
          gdStatus: [],
          gdProperty: 1,
          saleMode: [],
          checkList: [],
          radio: '1',
          orgIds: [],
          showIndex: 999,
          remark: '',
          exchangeFlag: 2,
          goodsShortCode: '',
          isPreferential: false,
          taxRateFlag: 1,
          rateFlag: '',
          taxRate: 0,
          extends1: '', // 图文详情
          extends2: '', // 产品参数
          extends3: '' // 售后保障
        },
        rules: {
          goodsCode: [{ required: true, message: '请获取商品编码', trigger: 'change' }],
          goodsName: [{ required: true, message: '请输入商品名称', trigger: 'change' }],
          unitId: [{ required: true, message: '请选择商品单位', trigger: 'change' }],
          cubage: [{ required: true, message: '请输入体积', trigger: 'change' }],
          weight: [{ required: true, message: '请输入重量', trigger: 'change' }],
          cashPledge: [{ required: true, message: '请输入押金', trigger: 'change' }],
          returnPrice: [{ required: true, message: '请输入退残单价', trigger: 'change' }],
          showIndex: [{ required: true, message: '请输入显示顺序', trigger: 'change' }],
          gdProperty: [{ required: true, message: '请选择商品性质', trigger: 'change' }]
        }
      }
    },
    computed: {
      ...mapGetters([
        'orgList'
      ])
    },
    async created() {
      await Promise.all([this.queryOptionsMap(), this.getTreeData(), this.getSpecListAll()])
    },
    methods: {
      async open(currentGoodsType, row, type) {
        if (type === 'edit') await this.getDefaultData(row)
        this.currentGoodsType = currentGoodsType
        if (currentGoodsType.goodsId) this.goodsId = currentGoodsType.goodsId
        this.type = type
        return new Promise(resolve => {
          this.resolve = resolve
          this.visible = true
        })
      },
      // 获取默认数据
      async getDefaultData(temp) {
        const res = await queryGoodsDefaultData({
          goodsId: temp.goodsId
        })
        if (res.data.goodsInfo) {
          this.temp = Object.assign(this.temp, res.data.goodsInfo)
          const goodsOptions = res.data.goodsInfo.options || 0
          this.sys_goods_edit_options_1 = (goodsOptions >> 1 & 0x01) === 1
          this.sys_goods_edit_options_2 = (goodsOptions >> 2 & 0x01) === 1
          this.sys_goods_edit_options_3 = (goodsOptions >> 3 & 0x01) === 1
          this.sys_goods_edit_options_4 = (goodsOptions >> 4 & 0x01) === 1
          this.sys_goods_edit_options_5 = (goodsOptions >> 5 & 0x01) === 1
          if (res.data.goodsInfo.gdStatus) {
            this.temp.gdStatus = this.gdStatusMap.filter(item => (1 << item.value & res.data.goodsInfo.gdStatus) > 0).map(it => it.value)
          }
          if (res.data.goodsInfo.saleMode) {
            this.temp.saleMode = this.goodsChannel.filter(item => (1 << item.value & res.data.goodsInfo.saleMode) > 0).map(it => it.value)
          }
          if (res.data.goodsInfo.isPreferential) {
            this.temp.isPreferential = true
          }
          if (res.data.goodsInfo.orgIds) {
            this.temp.radio = '2'
            this.temp.orgIds = res.data.goodsInfo.orgIds.split(',')
          }
          console.log(this.temp, 123)
        }
      },
      // 获取商品编码
      async getCode() {
        const res = await queryOrgCode({
          codeType: 6
        })
        this.temp.goodsCode = res.data
      },
      // 获取商品型号列表
      async getSpecListAll() {
        const res = await querySpecListAll({
          currentPage: 1, pageSize: 999
        })
        if (res.data.rows) this.specListAll = res.data.rows
      },
      // 查询枚举
      async queryOptionsMap() {
        const [res1, res2, res3, res4] = await Promise.all([mergeAsyncFunc(queryMap, { enumName: 'UnitType' }), mergeAsyncFunc(queryMap, { enumName: 'GdStatus' }), mergeAsyncFunc(queryMap, { enumName: 'GdProperty' }), mergeAsyncFunc(queryMap, { enumName: 'TaxRateFlag' })])
        this.unitIdMap = res1.data // 单位
        this.gdStatusMap = res2.data // 商品状态
        this.gdPropertyMap = res3.data
        this.taxRateFlagMap = res4.data
      },
      // 获取所属机构数据
      async getTreeData() {
        const data = this.orgList.map(item => ({
          label: item.name,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      // 选择所属机构
      selectTreeChange(value) {
        this.orgSNNo = value.orgSNNo
      },
      success() {
        this.$refs.dataForm.validate(valid => {
          if (!valid) {
            this.activeName = 'first'
            return
          }
          const unit = this.unitIdMap.find(item => item.value === this.temp.unitId)
          const spec = this.specListAll.find(item => item.specId === this.temp.specId)
          const params = {
            goodsCode: this.temp.goodsCode,
            goodsName: this.temp.goodsName,
            aliasName: this.temp.aliasName,
            cubage: this.temp.cubage,
            weight: this.temp.weight,
            cashPledge: this.temp.cashPledge,
            deliveryFun: this.temp.deliveryFun,
            floorFun: this.temp.floorFun,
            remark: this.temp.remark,
            exchangeFlag: this.temp.exchangeFlag || 0,
            gdProperty: this.temp.gdProperty,
            showIndex: this.temp.showIndex,
            goodsShortCode: this.temp.goodsShortCode,
            isPreferential: this.temp.isPreferential ? 1 : 0,
            taxRateFlag: this.temp.taxRateFlag,
            taxRate: this.temp.taxRate,
            returnPrice: this.temp.returnPrice,
            goodsId: this.temp.goodsId || 0,
            pricingMode: this.temp.pricingMode,
            unitId: this.temp.unitId,
            unitName: unit.desc
          }
          let saleMode = 0
          if (this.temp.saleMode.length > 0) {
            this.temp.saleMode.forEach(item => {
              saleMode |= Number(item)
            })
          }
          let gdStatus = 0
          if (this.temp.gdStatus.length > 0) {
            this.temp.gdStatus.forEach(item => {
              gdStatus |= Number(item)
            })
          }
          params.saleMode = saleMode
          params.gdStatus = gdStatus
          if (spec) {
            params.specId = this.temp.specId
            params.specAliasCode = spec.specAliasCode
            params.specName = spec.specName
            params.specCode = spec.specCode
          }
          if (this.goodsId === 0) {
            params.gTypeId = this.currentGoodsType.gtId
            params.gtSNNo = this.currentGoodsType.gtSNNo
            params.gtName = this.currentGoodsType.gtName
          }
          params.options |= 1 << 0
          if (this.sys_goods_edit_options_1) {
            params.options |= 1 << 1
          }
          if (this.sys_goods_edit_options_2) {
            params.options |= 1 << 2
          }
          if (this.sys_goods_edit_options_3) {
            params.options |= 1 << 3
          }
          if (this.sys_goods_edit_options_4) {
            params.options |= 1 << 4
          }
          if (this.sys_goods_edit_options_5) {
            params.options |= 1 << 5
          }
          if (this.temp.radio === '2') {
            params.orgIds = this.temp.orgIds.join(',')
          }
          if (this.$refs.fuEditor1.styleContent.length > 0) params.extends1 = this.$refs.fuEditor1.styleContent
          if (this.$refs.fuEditor2.styleContent.length > 0) params.extends2 = this.$refs.fuEditor2.styleContent
          if (this.$refs.fuEditor3.styleContent.length > 0) params.extends3 = this.$refs.fuEditor3.styleContent
          if (this.type === 'add') {
            this.add(params)
          } else {
            this.edit(params)
          }
        })
      },
      async add(params) {
        await goodsAdd(params)
        this.resolve()
        this.visible = false
        this.$notify({
          title: '提示',
          message: '新增成功',
          type: 'success',
          duration: 2000
        })
      },
      async edit(params) {
        await goodsAdd(params)
        this.resolve(this.temp)
        this.visible = false
        this.$notify({
          title: '提示',
          message: '更新成功',
          type: 'success',
          duration: 2000
        })
      },
      formatInput(e, name) {
        if (e.target.value) {
          this.temp[name] = Number(e.target.value).toFixed(2)
        }
      },
      reset() {
        this.type = 'add'
        this.activeName = 'first'
        this.additionTab = 'first'
        this.temp = {
          goodsCode: '',
          goodsName: '',
          unitId: '',
          aliasName: '',
          cubage: 0,
          weight: 0,
          specId: '',
          pricingMode: 1,
          deliveryFun: 0,
          floorFun: 0,
          cashPledge: 0,
          returnPrice: 0,
          gdStatus: [],
          gdProperty: 1,
          saleMode: [],
          checkList: [],
          radio: '1',
          orgIds: [],
          showIndex: 999,
          remark: '',
          exchangeFlag: 2,
          goodsShortCode: '',
          isPreferential: false,
          taxRateFlag: 1,
          rateFlag: '',
          taxRate: 0,
          extends1: '', // 图文详情
          extends2: '', // 产品参数
          extends3: '' // 售后保障
        }
        this.$nextTick(() => {
          this.$refs.dataForm.clearValidate()
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
.form {
  display: flex;
  flex-wrap: wrap;
  & /deep/ .el-form-item {
    width: 50%;
    padding-right: 10px;
    .el-form-item__content > .el-select {
      width: 100%;
    }
  }
  .block {
    width: 100%;
  }
}
.info-title {
  display: flex;
  align-items: center;
  margin-top: 10px;
  margin-bottom: 20px;
  .title-icon {
    display: inline-block;
    width: 4px;
    height: 18px;
    margin-right: 6px;
    background: $themeColor;
  }
  span {
    font-weight: 700;
    color: $themeColor;
  }
}
</style>
